package com.yuanli.cosmeticmirror.view.activity;

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.appcompat.widget.AppCompatCheckBox;

import com.bytedance.sdk.openadsdk.TTRewardVideoAd;
import com.comenjoysoft.baselibrary.util.DateUtil;
import com.comenjoysoft.baselibrary.util.SPUtils;
import com.kongzue.dialog.v3.CustomDialog;
import com.orhanobut.logger.Logger;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.builder.GSYVideoOptionBuilder;
import com.shuyu.gsyvideoplayer.listener.GSYVideoProgressListener;
import com.shuyu.gsyvideoplayer.listener.VideoAllCallBack;
import com.shuyu.gsyvideoplayer.utils.GSYVideoType;
import com.yuanli.cosmeticmirror.R;
import com.yuanli.cosmeticmirror.base.BaseActivity;
import com.yuanli.cosmeticmirror.base.MyApp;
import com.yuanli.cosmeticmirror.bean.FavoriteBean;
import com.yuanli.cosmeticmirror.bean.TutorialBean;
import com.yuanli.cosmeticmirror.bean.videoInfoBean;
import com.yuanli.cosmeticmirror.model.iview.IVideoView;
import com.yuanli.cosmeticmirror.persenter.VideoPersenter;
import com.yuanli.cosmeticmirror.widget.VideoView;
import com.yuanli.pangolinads.reward.RewardVideo;

import butterknife.BindView;
import butterknife.OnClick;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.tencent.qzone.QZone;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;
import comenjoy.com.imageloadlibrary.GlideUtil;

import static com.yuanli.cosmeticmirror.base.Constant.SP_USER_ACCOUNT;

/**
 *
 */
public class VideoPlayActivity extends BaseActivity implements IVideoView {

    @BindView(R.id.video_player)
    VideoView videoPlayer;
    @BindView(R.id.video_back)
    ImageView videoBack;
    @BindView(R.id.video_share)
    ImageView videoShare;
    @BindView(R.id.video_img)
    ImageView videoImg;
    @BindView(R.id.video_synopsis)
    TextView videoSynopsis;
    @BindView(R.id.video_like_cb)
    AppCompatCheckBox videoLikeCb;
    @BindView(R.id.video_favorite_cb)
    AppCompatCheckBox videoFavoriteCb;
    @BindView(R.id.video_look_num)
    TextView videoLookNum;
    private GSYVideoManager manager;
    private VideoPersenter persenter;
    private videoInfoBean.DataBean bean;
    private TutorialBean.DataBean dataBean;
    private FavoriteBean.DataBean data;
    private boolean isFavorite;
    private boolean isNotVip;
    private long mLastClickTime = 0;
    public final long TIME_INTERVAL = 1000L;
    @Override
    protected int getContentView() {
        //设置全屏显示
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        return R.layout.activity_video_play;
    }

    @Override
    protected void init(Bundle bundle) {
        persenter = new VideoPersenter(this, this);
    }

    @Override
    protected void initView() {
        GSYVideoOptionBuilder builder = new GSYVideoOptionBuilder();
        builder.setFullHideStatusBar(true).build(videoPlayer);
        GSYVideoType.setShowType(GSYVideoType.SCREEN_TYPE_FULL);

        videoPlayer.getThumbImageViewLayout().setVisibility(View.GONE);
        videoPlayer.getStartButton().setVisibility(View.GONE);
        //增加title
        videoPlayer.getTitleTextView().setVisibility(View.GONE);
        //设置返回键
        videoPlayer.getBackButton().setVisibility(View.GONE);
        //设置旋转
        //        orientationUtils = new OrientationUtils(this, videoPlayer);
        //        orientationUtils.setEnable(false);
        //设置全屏按键功能,这是使用的是选择屏幕，而不是全屏
        //        videoPlayer.getFullscreenButton().setOnClickListener((v) -> {
        //            orientationUtils.resolveByClick();
        //        });
        videoPlayer.getFullscreenButton().setVisibility(View.GONE);
        //是否可以滑动调整
        videoPlayer.setIsTouchWiget(false);
        videoPlayer.setShowFullAnimation(false);
        videoPlayer.setRotateViewAuto(false);
        videoPlayer.setRotateWithSystem(false);
        //设置返回按键功能
        videoPlayer.getBackButton().setOnClickListener(v ->
                this.onBackPressedSupport()
        );
        videoPlayer.setGSYVideoProgressListener((progress, secProgress, currentPosition, duration) -> {
            if (progress > 5) {
                if (isFavorite) {
                    if (!MyApp.IsVIP && data.getIsvip() == 1 && !isNotVip) {
                        //暂停播放，显示弹窗
                        GSYVideoManager.onPause();
                        getCustomDialogPaly();
                    }
                } else {
                    if (!MyApp.IsVIP && dataBean.getIsvip() == 1 && !isNotVip) {
                        GSYVideoManager.onPause();
                        getCustomDialogPaly();
                    }
                }
            }
        });

    }

    @Override
    public void initData() {
        bean = new videoInfoBean.DataBean();
        Intent intent = getIntent();
        isFavorite = intent.getBooleanExtra("isFavorite", false);
        if (isFavorite) {
            data = (FavoriteBean.DataBean) intent.getSerializableExtra("url");
            if (data != null) {
                bean.setCovingImg(data.getCovingimg());
                GlideUtil.getInstance().loadCircleImage(VideoPlayActivity.this, data.getCovingimg(), videoImg);
                persenter.getTutorialDetails(String.valueOf(data.getId()));
                persenter.addRecord(String.valueOf(data.getId()));
            }
        } else {
            dataBean = (TutorialBean.DataBean) intent.getSerializableExtra("url");
            if (dataBean != null) {
                bean.setCovingImg(dataBean.getCovingImg());
                GlideUtil.getInstance().loadCircleImage(VideoPlayActivity.this, dataBean.getCovingImg(), videoImg);
                persenter.getTutorialDetails(String.valueOf(dataBean.getId()));
                persenter.addRecord(String.valueOf(dataBean.getId()));
            }
        }

        if (isFavorite) {
            isNotVip = SPUtils.getInstance().getBoolean(data.getCovingimg(), false);
        } else {
            isNotVip = SPUtils.getInstance().getBoolean(dataBean.getCovingImg(), false);
        }
    }

    @Override
    protected void destroy() {
        Logger.d("onDestroy");
        GSYVideoManager.releaseAllVideos();
    }

    @Override
    protected void onPause() {
        super.onPause();
        videoPlayer.onVideoPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        videoPlayer.onVideoResume();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    public void onBackPressedSupport() {
        //释放所有
        if (videoPlayer != null) {
            videoPlayer.setVideoAllCallBack(null);
        }
        finish();
        super.onBackPressed();
    }


    /**
     * 视频界面  分享
     *
     * @return
     */
    private CustomDialog getCustomDialog() {
        return CustomDialog.show(VideoPlayActivity.this, R.layout.dialog_share_layout, (dialog, v) -> {
            LinearLayout shareQq = v.findViewById(R.id.share_qq);
            shareQq.setOnClickListener(v1 -> {
                persenter.share(bean.getTitle(), bean.getVideoUrl(), bean.getCovingImg(), QQ.NAME);
                dialog.doDismiss();
            });
            LinearLayout shareWechat = v.findViewById(R.id.share_wechat);
            shareWechat.setOnClickListener(v1 -> {
                persenter.share(bean.getTitle(), bean.getVideoUrl(), bean.getCovingImg(), Wechat.NAME);
                dialog.doDismiss();
            });
            LinearLayout shareWechatMoment = v.findViewById(R.id.share_wechat_moment);
            shareWechatMoment.setOnClickListener(v1 -> {
                persenter.share(bean.getTitle(), bean.getVideoUrl(), bean.getCovingImg(), WechatMoments.NAME);
                dialog.doDismiss();
            });
            LinearLayout shareSina = v.findViewById(R.id.share_sina);
            shareSina.setOnClickListener(v1 -> {
                showToast("暂未支持微博分享");
                dialog.doDismiss();
                //                persenter.share(dataBean.getTitle(), dataBean.getVideoUrl(), Sina.NAME);
            });
            LinearLayout shareQzone = v.findViewById(R.id.share_qzone);
            shareQzone.setOnClickListener(v1 -> {
                persenter.share(bean.getTitle(), bean.getVideoUrl(), bean.getCovingImg(), QZone.NAME);
                dialog.doDismiss();
            });
            LinearLayout shareMore = v.findViewById(R.id.share_more);
            shareMore.setOnClickListener(v1 -> {
                Intent intent = new Intent(Intent.ACTION_SEND);
                intent.setType("text/plain");
                intent.putExtra(Intent.EXTRA_TEXT, bean.getVideoUrl());
                startActivity(Intent.createChooser(intent, "分享到："));
                dialog.doDismiss();
            });
        }).setAlign(CustomDialog.ALIGN.DEFAULT);
    }

    @Override
    public void onSuccess(videoInfoBean object, int code) {
        if (code == VideoPersenter.TUTORIAL_DETAIL) {
            if (object != null && object.getData().get(0) != null) {
                videoInfoBean.DataBean dataBean = object.getData().get(0);
                bean.setCollectcount(dataBean.getCollectcount());
                bean.setGoodcount(dataBean.getGoodcount());
                bean.setCollectcount(dataBean.getCollectcount());
                bean.setId(dataBean.getId());
                bean.setIscollect(dataBean.getIscollect());
                bean.setIsgood(dataBean.getIsgood());
                bean.setScanCount(dataBean.getScanCount());
                bean.setTitle(dataBean.getTitle());
                bean.setVideoUrl(dataBean.getVideoUrl());
                if (!TextUtils.isEmpty(bean.getVideoUrl())) {
                    videoPlayer.setUp(bean.getVideoUrl(), false, "");
                    videoPlayer.startPlayLogic();
                }
                videoSynopsis.setText(bean.getTitle());
                videoLookNum.setText(String.valueOf(bean.getScanCount()));
                videoLikeCb.setChecked(bean.getIsgood() == 1);
                videoLikeCb.setText(String.valueOf(bean.getGoodcount()));
                videoFavoriteCb.setChecked(bean.getIscollect() == 1);
                videoFavoriteCb.setText(String.valueOf(bean.getCollectcount()));
            }
        } else if (code == VideoPersenter.TUTORIAL_LIKE) {
            videoLikeCb.setText(String.valueOf(Integer.parseInt(videoLikeCb.getText().toString()) + 1));
        } else if (code == VideoPersenter.TUTORIAL_COLLECT) {
            videoFavoriteCb.setText(String.valueOf(Integer.parseInt(videoFavoriteCb.getText().toString()) + 1));
        } else if (code == VideoPersenter.TUTORIAL_CANCEL_LIKE) {
            videoLikeCb.setText(String.valueOf(Integer.parseInt(videoLikeCb.getText().toString()) - 1));
        } else if (code == VideoPersenter.TUTORIAL_CANCEL_COLLECT) {
            videoFavoriteCb.setText(String.valueOf(Integer.parseInt(videoFavoriteCb.getText().toString()) - 1));
        }
    }

    @Override
    public void onError(String msg, int code) {
        if (code == VideoPersenter.TUTORIAL_DETAIL) {
            showToast(msg);
        } else if (code == VideoPersenter.TUTORIAL_LIKE) {
            videoLikeCb.setChecked(false);
        } else if (code == VideoPersenter.TUTORIAL_COLLECT) {
            videoFavoriteCb.setChecked(false);
        } else if (code == VideoPersenter.TUTORIAL_CANCEL_LIKE) {
            videoLikeCb.setChecked(true);
        } else if (code == VideoPersenter.TUTORIAL_CANCEL_COLLECT) {
            videoFavoriteCb.setChecked(true);
        }
    }

    @Override
    public Context getActivity() {
        return this;
    }

    @OnClick({R.id.video_back, R.id.video_share, R.id.video_like_cb, R.id.video_favorite_cb})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.video_back:
                onBackPressedSupport();
                break;
            case R.id.video_share:
                if (bean != null) {
                    getCustomDialog();
                } else {
                    showToast("视频数据加载错误");
                }
                break;
            case R.id.video_like_cb:
                if (bean == null) {
                    showToast("视频数据加载错误");
                    return;
                }
                if (videoLikeCb.isChecked()) {
                    persenter.like(String.valueOf(bean.getId()));
                } else {
                    persenter.cancelLike(String.valueOf(bean.getId()));
                }
                break;
            case R.id.video_favorite_cb:
                if (bean == null) {
                    showToast("视频数据加载错误");
                    return;
                }
                if (videoFavoriteCb.isChecked()) {
                    persenter.collect(String.valueOf(bean.getId()));
                } else {
                    persenter.cancelCollect(String.valueOf(bean.getId()));
                }
                break;
            default:
                break;
        }
    }

    /**
     * 视频播放界面  提示需要会员
     *
     * @return
     */
    private CustomDialog getCustomDialogPaly() {

        return CustomDialog.show(VideoPlayActivity.this, R.layout.dialog_member_warm, (dialog, v) -> {
            TextView btnOk = v.findViewById(R.id.member_enter);
            TextView btnAd = v.findViewById(R.id.member_to_ad);
            TextView btncancel = v.findViewById(R.id.member_cancel);
            btnAd.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    long nowTime = System.currentTimeMillis();
                    if (nowTime - mLastClickTime < TIME_INTERVAL) {
                        // do something
                        return;
                    }
                    mLastClickTime = nowTime;
                    RewardVideo.loadRewardedAd(SPUtils.getInstance().getString(SP_USER_ACCOUNT), VideoPlayActivity.this, new TTRewardVideoAd.RewardAdInteractionListener() {
                        @Override
                        public void onAdShow() {

                        }

                        @Override
                        public void onAdVideoBarClick() {

                        }

                        @Override
                        public void onAdClose() {
                            Logger.d("onAdClose");
                            dialog.doDismiss();
                            if (isNotVip) {
                                GSYVideoManager.onResume();
                            } else {
                                finish();
                            }
                        }

                        @Override
                        public void onVideoComplete() {
                            isNotVip = true;
                            if (isFavorite) {
                                data.setIsvip(0);
                                SPUtils.getInstance().put(data.getCovingimg(), true);
                            } else {
                                dataBean.setIsvip(0);
                                SPUtils.getInstance().put(dataBean.getCovingImg(), true);
                            }
                            Logger.d("onVideoComplete");
                        }

                        @Override
                        public void onVideoError() {
                            isNotVip = false;
                            dialog.doDismiss();
                            finish();
                        }

                        @Override
                        public void onRewardVerify(boolean b, int i, String s) {

                        }

                        @Override
                        public void onSkippedVideo() {

                        }
                    });
                }
            });
            btnOk.setOnClickListener(v1 -> {
                startActivity(new Intent(VideoPlayActivity.this, MemberActivity.class));
                this.onBackPressedSupport();
                dialog.doDismiss();
            });
            btncancel.setOnClickListener(v1 -> {
                this.onBackPressedSupport();
                dialog.doDismiss();
            });
        }).setAlign(CustomDialog.ALIGN.DEFAULT).setCancelable(false);
    }
}
